package com.woniu.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.woniu.dao.CreditRefundDao;
import com.woniu.entity.CreContract;
import com.woniu.entity.CreRefund;
import com.woniu.entity.CreRemit;
import com.woniu.entity.CreUser;
import com.woniu.service.*;
import com.woniu.tool.MailProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 2022-9-24 15:40:48
 * 合同控制
 */
@Api("前台合同管理")
@Component("contract")
@RestController
@RequestMapping("/credit/contract")
public class CreditContractController extends BaseController {
    @Autowired
    private CreditContractService creditContractService;

    @Autowired
    private CreditOrderService creditOrderService;
    @Autowired
    private CreditUserService creditUserService;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    CreditRemitService creditRemitService;
    @Autowired
    CreditRefundService creditRefundService;

    @Autowired
    CreditRefundDao creditRefundDao;

    /*
     * 合同查询
     * */
    @ApiOperation("合同查询")
    @GetMapping("/findAll")
    public TableDataInfo findAllContract(CreContract creContract) {
        startPage();
        List<CreContract> list = creditContractService.findAllContract(creContract);
        return getDataTable(list);
    }

    /**
     * 导出合同列表
     */
    @ApiOperation("导出合同列表")
    @Log(title = "导出合同数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CreContract creContract) {
        List<CreContract> list = creditContractService.findAllContract(creContract);
        ExcelUtil<CreContract> util = new ExcelUtil<CreContract>(CreContract.class);
        util.exportExcel(response, list, "合同数据");
    }

    /*
     * 合同模糊搜索
     * */
    @ApiOperation("合同模糊搜索")
    @RequestMapping("/searchContract")
    public TableDataInfo searchContract(CreContract creContract) {
        startPage();
        List<CreContract> list = creditContractService.searchContract(creContract);
        return getDataTable(list);
    }

    /*
     * 合同生成及发送
     * */
    @ApiOperation("合同生成及发送")
    @PostMapping("/addContract")
    public AjaxResult addContract(@RequestBody CreContract creContract) {
        String email = creditRefundDao.checkEmailByUserId(creContract.getUserId());
        mailProperties.sendMail(email, "合同", "尊敬的用户恭喜您获得我们的贷款服务，请上app签署贷款协议");
        return toAjax(creditContractService.addContract(creContract));
    }

    //author：李敬
    @ApiOperation("合同列表")
    @GetMapping("/list")
    public TableDataInfo list(CreContract creContract) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        Integer A = userId.intValue();
        List<CreContract> list = creditContractService.selectContractList(A);
        return getDataTable(list);
    }

    //author：李敬
    @ApiOperation("签署合同多表查询")
    @GetMapping("/userDetail/{orderId}")

    public AjaxResult getUserDetail(@PathVariable(value = "orderId", required = false) int orderId) {

        AjaxResult ajax = AjaxResult.success();
        CreContract creContract = creditContractService.selectContractdetail(orderId);
        Long userId = SecurityUtils.getUserId();
        Integer A = userId.intValue();
        CreUser creUser = creditUserService.findUserById(A);
        ajax.put("creuser", "creUser");
        ajax.put(AjaxResult.DATA_TAG, creContract);
        return ajax;
    }

    //author：李敬
    @ApiOperation("签署时改变状态")
    @PutMapping("/changeStatus")
    public AjaxResult edit(@Validated @RequestBody CreContract creContract) {
        Long userId = SecurityUtils.getUserId();
        Integer A = userId.intValue();

        CreContract creContract1 = creditContractService.selectContractdetail(creContract.getOrderId());

//        初始需要字段：订单id，合同id，打款金额
        CreRemit creRemit = new CreRemit();
        creRemit.setContractId(creContract1.getId());
        creRemit.setOrderId(creContract1.getOrderId());
        creRemit.setRemitMoney(creContract1.getCreOrder().getApplymoney());
        creditRemitService.addPaymentData(creRemit);
        CreRefund creRefund = new CreRefund();
        creRefund.setContractId(creContract1.getId());
        creRefund.setUserId(creContract1.getUserId());
        creRefund.setOrderId(creContract1.getOrderId());
        CreUser creUser = creditUserService.selectUserDetById(Long.valueOf(A));
        creRefund.setUserPhone(creUser.getUserPhone());
        creRefund.setRealName(creUser.getRealName());
        creRefund.setEscrow(creContract1.getContractSource());
        creRefund.setLoanTerm(creContract1.getCreOrder().getLoanTerm());
        creRefund.setPaymentMethod(creContract1.getCreOrder().getPaymentMethod());
        creRefund.setRefundProduct(creContract1.getCreOrder().getProductName());
        creRefund.setShouldTotal(creContract1.getCreOrder().getApplymoney());
        creRefund.setConsultingRate(creContract1.getCreProduct().getConsultingRate());
        creRefund.setMonthRate(creContract1.getCreProduct().getMonthRate());
        creRefund.setMarginRate(creContract1.getCreProduct().getMarginRate());

//        还款次数
        // TODO: 2022/10/6 还款次数疑问
        creRefund.setRefundCount(Integer.parseInt(creContract1.getCreOrder().getLoanTerm()));
        creditRefundService.addRefund(creRefund);
        return toAjax(creditContractService.updateContractStatus(creContract1.getId()));
    }

    /**
     * 定时任务，判断合同是否失效
     */
    public void contractStatus() {
        int i = creditContractService.isOutTime();
        if (i > 0) {
            int c = creditContractService.updateConStatus();
            int o = creditContractService.updateOrdStatus();
            if (c > 0 && o > 0) {
                System.out.println("已有" + c + "条合同失效");
                return;
            }
        }
        System.out.println("未有失效合同");
    }


}
